package cn.ug.pay.service.impl;

import cn.ug.activity.bean.GoldShopBean;
import cn.ug.analyse.bean.request.MemberAnalyseMsgParamBean;
import cn.ug.bean.Result;
import cn.ug.bean.ResultItem;
import cn.ug.bean.base.DataOtherTable;
import cn.ug.bean.base.DataTable;
import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.config.FundRateConfig;
import cn.ug.config.RedisGlobalLock;
import cn.ug.core.SerializeObjectError;
import cn.ug.core.ensure.Ensure;
import cn.ug.enums.*;
import cn.ug.feign.*;
import cn.ug.mall.bean.OrderLogisticsBean;
import cn.ug.msg.mq.Msg;
import cn.ug.msg.mq.WxMessageParamBean;
import cn.ug.msg.mq.WxNotifyData;
import cn.ug.pay.bean.BillBean;
import cn.ug.pay.bean.GoldExtractionBean;
import cn.ug.pay.bean.GoldRecordBean;
import cn.ug.pay.bean.MemberGoldBean;
import cn.ug.pay.bean.request.ExtractionGoldOtherBean;
import cn.ug.pay.bean.request.ExtractionGoldPayBean;
import cn.ug.pay.bean.request.TradeCommonParamBean;
import cn.ug.pay.bean.response.*;
import cn.ug.pay.bean.status.CommonConstants;
import cn.ug.pay.bean.status.PayDistributePrefix;
import cn.ug.pay.bean.status.TbillStatusEnum;
import cn.ug.pay.bean.status.TradeStatus;
import cn.ug.pay.bean.type.BillType;
import cn.ug.pay.bean.type.TradeType;
import cn.ug.pay.component.PayCommon;
import cn.ug.pay.component.YeePayCommons;
import cn.ug.pay.mapper.*;
import cn.ug.pay.mapper.entity.*;
import cn.ug.pay.service.BillService;
import cn.ug.pay.service.ExtractionGoldService;
import cn.ug.pay.service.MemberAccountService;
import cn.ug.product.bean.response.ProductFindBean;
import cn.ug.service.impl.BaseServiceImpl;
import cn.ug.util.BigDecimalUtil;
import cn.ug.util.DateUtils;
import cn.ug.util.SerialNumberWorker;
import cn.ug.util.UF;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.dozer.DozerBeanMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static cn.ug.config.QueueName.QUEUE_MEMBER_ANALYSE;
import static cn.ug.config.QueueName.QUEUE_MSG_SEND;
import static cn.ug.config.QueueName.QUEUE_MSG_WX_SEND;

@Service
public class ExtractionGoldServiceImpl extends BaseServiceImpl implements ExtractionGoldService {

    private static Logger logger = LoggerFactory.getLogger(ExtractionGoldServiceImpl.class);

    @Resource
    private ProcessTemplateService processTemplateService;

    @Resource
    private RateSettingsService rateSettingsService;

    @Resource
    private RedisGlobalLock redisGlobalLock;

    @Resource
    private BankCardMapper bankCardMapper;

    @Resource
    private MemberAccountMapper memberAccountMapper;

    @Resource
    private TradeMapper tradeMapper;

    @Resource
    private BillService billService;

    @Resource
    private PayCommon payCommon;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Resource
    private BankInfoMapper bankInfoMapper;

    @Autowired
    private BillMapper billMapper;

    @Autowired
    private FundRateConfig fundRateConfig;

    @Resource
    private DozerBeanMapper dozerBeanMapper;

    @Resource
    private YeePayCommons yeePayCommons;

    @Resource
    private EntityExtractGoldMapper entityExtractGoldMapper;

    @Resource
    private PayTbillMapper payTbillMapper;

    @Resource
    private PayTbillStatusMapper payTbillStatusMapper;

    @Resource
    private PayTbillStatisticsMapper payTbillStatisticsMapper;

    @Resource
    private ProductService productService;

    @Resource
    private KdService kdService;

    @Resource
    private GoldShopService goldShopService;

    @Resource
    private ExtractionOfflineMapper extractionOfflineMapper;

    @Override
    public DataTable<ExtractGoldFindBean> query(String order, String sort, int pageNum, int pageSize, Integer type,
                                                String orderNo, String productName, String loginName,
                                                Integer minGram, Integer maxGram,
                                                LocalDateTime addTimeMin, LocalDateTime addTimeMax, Integer status,String shopName) {
        Page<GoldRecordBean> page = PageHelper.startPage(pageNum, pageSize);
        List<ExtractGoldFindBean> resultList = query(order, sort, addTimeMin, addTimeMax, loginName, minGram, maxGram, null, productName, orderNo, null, status,type,shopName);
        return new DataTable<>(page.getPageNum(), page.getPageSize(), page.getTotal(), resultList);
    }

    /**
     * 获取数据列表
     *
     * @param order       排序字段
     * @param sort        排序方式 desc或asc
     * @param addTimeMin  最小创建时间
     * @param addTimeMax  最大创建时间
     * @param loginName
     * @param minGram
     * @param maxGram
     * @param keyword
     * @param productName
     * @param orderNo
     * @param memberId
     * @param status      0-交易失败,1-已预约， 2-待收货， 3-已取消， 4-已完成
     * @param type        类型：1:快递 2:门店
     * @return
     */
    private List<ExtractGoldFindBean> query(String order, String sort, LocalDateTime addTimeMin, LocalDateTime addTimeMax,
                                            String loginName, Integer minGram, Integer maxGram, String keyword, String productName, String orderNo,
                                            String memberId, Integer status,Integer type,String shopName) {
        if (null != addTimeMax) {
            // 加一天减一秒
            addTimeMax = addTimeMax.plusDays(1).minusSeconds(1);
        }
        if (type == 1){
            List<ExtractGoldFindBean> list = entityExtractGoldMapper.queryList(
                    getParams(keyword, order, sort)
                            .put("addTimeMin", addTimeMin)
                            .put("addTimeMax", addTimeMax)
                            .put("loginName", loginName)
                            .put("minGram", minGram)
                            .put("maxGram", maxGram)
                            .put("productName", productName)
                            .put("orderNo", orderNo)
                            .put("memberId", memberId)
                            .put("status", status)
                            .toMap());
            return list;
        }else {
            List<ExtractGoldFindBean> list = extractionOfflineMapper.queryList(
                    getParams(keyword, order, sort)
                            .put("addTimeMin", addTimeMin)
                            .put("addTimeMax", addTimeMax)
                            .put("loginName", loginName)
                            .put("minGram", minGram)
                            .put("maxGram", maxGram)
                            .put("productName", productName)
                            .put("orderNo", orderNo)
                            .put("memberId", memberId)
                            .put("status", status)
                            .put("shopName", shopName)
                            .toMap());
            return list;
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public SerializeObject closeOrder(ExtractionGoldOtherBean submit) {
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("orderNo", submit.getOrderNo());
        requestMap.put("closeRemark", submit.getCloseRemark());
        requestMap.put("closeTime", DateUtils.getCurrentDateStr());
        //订单取消  状态设置为  3-已取消
        requestMap.put("status", ExtractGoldStatusEnum.CANCEL.getStatus());
        requestMap.put("readed", 0);
        if (submit.getType() == null || submit.getType() == 1) {
            ExtractGoldBaseBean extractGoldBaseBean = entityExtractGoldMapper.findByOrderNo(submit.getOrderNo());
            if (extractGoldBaseBean != null) {
                int rows = entityExtractGoldMapper.update(requestMap);
                Ensure.that(rows).isLt(1, "00000005");
                //发送微信，短信相关通知
                sendNotice(extractGoldBaseBean,submit.getOrderNo());
                return new SerializeObject<>(ResultType.NORMAL, "00000001");
            }
        }else {
            ExtractGoldBaseBean extractGoldBaseBean = extractionOfflineMapper.findByOrderNo(submit.getOrderNo());
            if (extractGoldBaseBean != null) {
                int rows = extractionOfflineMapper.update(requestMap);
                Ensure.that(rows).isLt(1, "00000005");
                sendNotice(extractGoldBaseBean,submit.getOrderNo());
                return new SerializeObject<>(ResultType.NORMAL, "00000001");
            }
        }
        return new SerializeObjectError("00000003");
    }

    @Override
    public SerializeObject remarkOrder(ExtractionGoldOtherBean submit) {
        //快递提金
        if (submit.getType() == null || submit.getType() == 1) {
            ExtractGoldBaseBean extractGoldBaseBean = entityExtractGoldMapper.findByOrderNo(submit.getOrderNo());
            if (extractGoldBaseBean == null) {
                return new SerializeObjectError("00000003");
            }
            Map<String, Object> requestMap = new HashMap<>();
            requestMap.put("orderNo", submit.getOrderNo());
            requestMap.put("remark", submit.getRemark());
            int rows = entityExtractGoldMapper.update(requestMap);
            Ensure.that(rows).isLt(1, "00000005");
            return new SerializeObject<>(ResultType.NORMAL, "00000001");
        } else {
            //门店提金
            ExtractGoldBaseBean extractGoldBaseBean = extractionOfflineMapper.findByOrderNo(submit.getOrderNo());
            if (extractGoldBaseBean == null) {
                return new SerializeObjectError("00000003");
            }
            Map<String, Object> requestMap = new HashMap<>();
            requestMap.put("orderNo", submit.getOrderNo());
            requestMap.put("remark", submit.getRemark());
            int rows = extractionOfflineMapper.update(requestMap);
            Ensure.that(rows).isLt(1, "00000005");
            return new SerializeObject<>(ResultType.NORMAL, "00000001");
        }
    }

    @Override
    public SerializeObject findRemark(String orderNo, Integer type) {
        if (type == null || type == 1) {
            ExtractGoldBaseBean extractGoldBaseBean = entityExtractGoldMapper.findByOrderNo(orderNo);
            if (extractGoldBaseBean == null) {
                return new SerializeObjectError("00000003");
            }
            return new SerializeObject<>(ResultType.NORMAL, extractGoldBaseBean);
        } else {
            ExtractGoldBaseBean extractGoldBaseBean = extractionOfflineMapper.findByOrderNo(orderNo);
            if (extractGoldBaseBean == null) {
                return new SerializeObjectError("00000003");
            }
            return new SerializeObject<>(ResultType.NORMAL, extractGoldBaseBean);
        }
    }

    @Override
    public SerializeObject orderDelivery(ExtractionGoldOtherBean submit) {
        ExtractGoldBaseBean extractGoldBaseBean = entityExtractGoldMapper.findByOrderNo(submit.getOrderNo());
        if (extractGoldBaseBean != null && extractGoldBaseBean.getStatus() == ExtractGoldStatusEnum.SUBSCRIBE.getStatus()) {
            Map<String, Object> requestMap = new HashMap<>();
            requestMap.put("orderNo", submit.getOrderNo());
            requestMap.put("status", ExtractGoldStatusEnum.WAIT_TAKE.getStatus());
            requestMap.put("deliverTime", DateUtils.getCurrentDateStr());
            requestMap.put("logisticsName", "顺丰快递");
            requestMap.put("logisticsNo", submit.getLogisticsNo());
            requestMap.put("readed", 0);
            int rows = entityExtractGoldMapper.update(requestMap);
            Ensure.that(rows).isLt(1, "00000005");
            return new SerializeObject<>(ResultType.NORMAL, "00000001");
        }
        return new SerializeObjectError("00000003");
    }


    @Override
    public SerializeObject orderTrack(String orderNo) {
        ExtractGoldBaseBean extractGoldBaseBean = entityExtractGoldMapper.findByOrderNo(orderNo);
        if (extractGoldBaseBean == null) {
            return new SerializeObjectError("00000003");
        }

        if (StringUtils.isNotBlank(extractGoldBaseBean.getLogisticsNo())) {
            if (extractGoldBaseBean.getStatus() == ExtractGoldStatusEnum.FINISH.getStatus()) {
                String data = extractGoldBaseBean.getData();
                if (data != null) {
                    List<OrderLogisticsBean> logisticsBeans = JSONObject.parseArray(data, OrderLogisticsBean.class);
                    int index = logisticsBeans == null ? 0 : logisticsBeans.size();
                    logisticsBeans.add(index, new OrderLogisticsBean("订单付款成功", DateUtils.strToDate(extractGoldBaseBean.getSuccessTime())));
                    logisticsBeans.add(index + 1, new OrderLogisticsBean("订单已提交等待支付", DateUtils.strToDate(extractGoldBaseBean.getAddTimeString())));
                    return new SerializeObject<>(ResultType.NORMAL, "00000001", logisticsBeans);
                }
            }


            Map<String, Object> requestMap = new HashMap<>();
            List<OrderLogisticsBean> list = new ArrayList<>();
            if (extractGoldBaseBean.getStatus() != ExtractGoldStatusEnum.FINISH.getStatus()) {
                SerializeObject<Result> obj = kdService.queryOrderTrace(KD100LogisticsEnum.SHUN_FENG.number(), extractGoldBaseBean.getLogisticsNo());
                if (obj != null && obj.getData() != null) {
                    Result result = obj.getData();
                    if (result != null && "200".equals(result.getStatus())) {
                        int state = Integer.parseInt(result.getState());
                        String desc = LogisticsStatusEnum.get(state).desc();
                        ArrayList<ResultItem> data = result.getData();
                        if (CollectionUtils.isNotEmpty(data)) {
                            ResultItem resultItem = data.get(0);
                            resultItem.setContext(desc + "，" + resultItem.getContext());
                            for (ResultItem item : data) {
                                OrderLogisticsBean bean = new OrderLogisticsBean();
                                bean.setContext(item.getContext());
                                bean.setTime(UF.strToDate(item.getFtime(), "yyyy-MM-dd HH:mm:ss"));
                                list.add(bean);
                            }
                        }
                        //已签收
                        if (state == 3) {
                            requestMap.put("status", ExtractGoldStatusEnum.FINISH.getStatus());
                            requestMap.put("finalTime", DateUtils.dateToStr(list.get(0).getTime(), "yyyy-MM-dd hh:mm:ss"));
                            requestMap.put("readed", 0);
                            //提金完成后操作
                            extractionFinished(extractGoldBaseBean.getTbillNo(), extractGoldBaseBean.getMemberId());
                        }
                    }
                }
            }
            String data = JSON.toJSONString(list);
            list.add(new OrderLogisticsBean("订单付款成功", DateUtils.strToDate(extractGoldBaseBean.getSuccessTime())));
            list.add(new OrderLogisticsBean("订单已提交等待支付", DateUtils.strToDate(extractGoldBaseBean.getAddTimeString())));
            requestMap.put("data", data);
            requestMap.put("orderNo", orderNo);
            entityExtractGoldMapper.update(requestMap);
            return new SerializeObject<>(ResultType.NORMAL, "00000001", list);
        }
        return new SerializeObject<>(ResultType.NORMAL, "00000001");
    }

    @Override
    public SerializeObject findOrder(String orderNo, Integer type) {
        if (type==null || type == 1) {
            orderTrack(orderNo);
            ExtractGoldBaseBean extractGoldBaseBean = entityExtractGoldMapper.findByOrderNo(orderNo);
            if (extractGoldBaseBean != null) {
                ExtractGoldFindBean extractGoldFindBean = entityExtractGoldMapper.findOrder(orderNo);
                SerializeObject<ProductFindBean> result = productService.queryProductById(extractGoldFindBean.getProductId());
                if (result != null && result.getCode() == 200) {
                    if (result.getData() != null) {
                        ProductFindBean productFindBean = result.getData();
                        extractGoldFindBean.setProductImgUrl(productFindBean.getImg());
                    }
                }
                return new SerializeObject<>(ResultType.NORMAL, "00000001", extractGoldFindBean);
            }
        }else {
            ExtractGoldBaseBean extractGoldBaseBean = extractionOfflineMapper.findByOrderNo(orderNo);
            if (extractGoldBaseBean != null) {
                ExtractGoldFindBean extractGoldFindBean = extractionOfflineMapper.findOrder(orderNo);
                SerializeObject<ProductFindBean> result = productService.queryProductById(extractGoldFindBean.getProductId());
                if (result != null && result.getCode() == 200) {
                    if (result.getData() != null) {
                        ProductFindBean productFindBean = result.getData();
                        extractGoldFindBean.setProductImgUrl(productFindBean.getImg());
                    }
                }
                return new SerializeObject<>(ResultType.NORMAL, "00000001", extractGoldFindBean);
            }
        }
        return new SerializeObjectError("00000003");
    }

    @Override
    public DataTable<ExtractGoldUserStatisticsBean> findUserStatistics(int pageNum, int pageSize, String memberName, String mobile,
                                                                       Integer minGram, Integer maxGram) {
        Page<GoldRecordBean> page = PageHelper.startPage(pageNum, pageSize);
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("memberName", memberName);
        requestMap.put("mobile", mobile);
        requestMap.put("minGram", minGram);
        requestMap.put("maxGram", maxGram);
        List<ExtractGoldUserStatisticsBean> extractGoldUserStatisticsBeanList = entityExtractGoldMapper.findUserStatistics(requestMap);
        return new DataTable<>(page.getPageNum(), page.getPageSize(), page.getTotal(), extractGoldUserStatisticsBeanList);
    }

    @Override
    public DataTable<ExtractGoldFindBean> queryDetail(int pageNum, int pageSize, String memberId) {
        Page<GoldRecordBean> page = PageHelper.startPage(pageNum, pageSize);
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("memberId", memberId);
        requestMap.put("status", ExtractGoldStatusEnum.FINISH.getStatus());
        List<ExtractGoldFindBean> resultList = entityExtractGoldMapper.queryDetail(requestMap);
        return new DataTable<>(page.getPageNum(), page.getPageSize(), page.getTotal(), resultList);
    }

    @Override
    public SerializeObject extractionSucceed(String orderNo, Integer type,Integer status) {
        ExtractGoldBaseBean extractGoldBaseBean = extractionOfflineMapper.findByOrderNo(orderNo);
        if (extractGoldBaseBean == null) {
            return new SerializeObjectError("00000003");
        }

        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("orderNo", orderNo);
        requestMap.put("status", status);
        if (ExtractGoldStatusEnum.FINISH.getStatus() == status){
            requestMap.put("finalTime", DateUtils.getCurrentDateStr());
        }
        requestMap.put("readed", 0);
        int rows = extractionOfflineMapper.update(requestMap);
        Ensure.that(rows).isLt(1, "00000005");
        //提金完成后操作
        if (status == 4){
            extractionFinished(extractGoldBaseBean.getTbillNo(), extractGoldBaseBean.getMemberId());
        }
        return new SerializeObject<>(ResultType.NORMAL, "00000001");
    }

    @Override
    public GoldExtractionBean selectByTbillNO(String tbillNO) {
        if (StringUtils.isNotBlank(tbillNO)) {
            return entityExtractGoldMapper.selectByTbillNO(tbillNO);
        }
        return null;
    }

    @Override
    public void succeed(String orderNo, Integer type) {
        logger.info("---------提金支付成功---------订单号：" + orderNo + "  类型：" + type);
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("successTime", DateUtils.getCurrentDateStr());
        requestMap.put("orderNo", orderNo);
        if (type == 1) {
            ExtractGoldBaseBean extractGoldBaseBean = entityExtractGoldMapper.findByOrderNo(orderNo);
            if (extractGoldBaseBean != null) {
                int rows = entityExtractGoldMapper.update(requestMap);
                Ensure.that(rows).isLt(1, "00000005");
                payExtractionSuccess(extractGoldBaseBean.getTbillNo(), extractGoldBaseBean.getMemberId());
            }
        } else {
            ExtractGoldBaseBean extractGoldBaseBean = extractionOfflineMapper.findByOrderNo(orderNo);
            if (extractGoldBaseBean != null) {
                int rows = extractionOfflineMapper.update(requestMap);
                Ensure.that(rows).isLt(1, "00000005");
                payExtractionSuccess(extractGoldBaseBean.getTbillNo(), extractGoldBaseBean.getMemberId());
            }
        }
    }


    @Override
    public int countUnread() {
        return entityExtractGoldMapper.countUnread();
    }

    @Override
    public void read(String orderNo,Integer type) {
        Map<String, Object> requestMap = new HashMap<>();
        //已读
        requestMap.put("readed", 1);
        requestMap.put("orderNo", orderNo);
        if (type==null || type==1){
            ExtractGoldBaseBean extractGoldBaseBean = entityExtractGoldMapper.findByOrderNo(orderNo);
            if (extractGoldBaseBean != null) {
                int rows = entityExtractGoldMapper.update(requestMap);
                Ensure.that(rows).isLt(1, "00000005");
            }
        }else {
            ExtractGoldBaseBean extractGoldBaseBean = extractionOfflineMapper.findByOrderNo(orderNo);
            if (extractGoldBaseBean != null) {
                int rows = extractionOfflineMapper.update(requestMap);
                Ensure.that(rows).isLt(1, "00000005");
            }
        }
    }

    @Override
    public DataOtherTable<ExtractGoldMyBean> findList(String memberId, int pageNum, int pageSize, Integer status) {
        Page<GoldRecordBean> page = PageHelper.startPage(pageNum, pageSize);
        List<ExtractGoldMyBean> resultList = entityExtractGoldMapper.findList(memberId, status);
        List<Map<String, Object>> resultListMap = entityExtractGoldMapper.findNotRead(memberId);
        Map resultMap = new HashMap<>();
        //初始化
        resultMap.put("subscribeFlag", 0);
        resultMap.put("waitTakeFlag", 0);
        resultMap.put("cancelFlag", 0);
        resultMap.put("finishFlag", 0);

        if (!org.springframework.util.CollectionUtils.isEmpty(resultListMap)) {
            for (Map<String, Object> map : resultListMap) {
                if (ExtractGoldStatusEnum.SUBSCRIBE.getStatus() == (Integer) map.get("status")) {
                    resultMap.put("subscribeFlag", map.get("subscribeFlag"));
                }

                if (ExtractGoldStatusEnum.WAIT_TAKE.getStatus() == (Integer) map.get("status")) {
                    resultMap.put("waitTakeFlag", map.get("waitTakeFlag"));
                }

                if (ExtractGoldStatusEnum.CANCEL.getStatus() == (Integer) map.get("status")) {
                    resultMap.put("cancelFlag", map.get("cancelFlag"));
                }

                if (ExtractGoldStatusEnum.FINISH.getStatus() == (Integer) map.get("status")) {
                    resultMap.put("finishFlag", map.get("finishFlag"));
                }
            }
        }
        return new DataOtherTable<>(page.getPageNum(), page.getPageSize(), page.getTotal(), resultList, resultMap);
    }


    @Override
    public SerializeObject<ExtractGoldDetail> findDetail(String orderNo, Integer type) {
        if (type != null && type == 1) {
            orderTrack(orderNo);
            ExtractGoldBaseBean extractGoldBaseBean = entityExtractGoldMapper.findByOrderNo(orderNo);
            if (extractGoldBaseBean != null) {
                ExtractGoldDetail extractGoldDetail = entityExtractGoldMapper.findDetail(orderNo);
                return new SerializeObject<>(ResultType.NORMAL, extractGoldDetail);
            }
        }else {
            ExtractGoldBaseBean extractGoldBaseBean = extractionOfflineMapper.findByOrderNo(orderNo);

            if (extractGoldBaseBean != null) {
                ExtractGoldDetail extractGoldDetail = extractionOfflineMapper.findDetail(orderNo);
                extractGoldDetail.setAddress(extractGoldBaseBean.getShopAddress());
                extractGoldDetail.setShopAddress(extractGoldBaseBean.getShopAddress());
                extractGoldDetail.setContactMobile(extractGoldBaseBean.getContactMobile());
                return new SerializeObject<>(ResultType.NORMAL, extractGoldDetail);
            }
        }
        return new SerializeObjectError("00000003");
    }

    @Override
    public SerializeObject findFee(String orderNO) {
        PayTbill payTbill = payTbillMapper.selectByOrderNO(orderNO);
        if (payTbill == null) {
            return new SerializeObjectError("00000003");
        }
        SerializeObject<ProductFindBean> result = productService.queryProductById(payTbill.getProductId());
        Map<String, Object> resultMap = new HashMap<>();
        if (result != null) {
            //获取加工费信息
            SerializeObject serializeObject = processTemplateService.find(result.getData().getProcessId());
            if (serializeObject != null && serializeObject.getCode() == 200) {
                JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(serializeObject.getData()));
                BigDecimal processCost = jsonObject.getBigDecimal("processCost");
                int disCount = jsonObject.getInteger("disCount");
                BigDecimal cost = processCost.multiply(new BigDecimal(disCount)).divide(new BigDecimal(100));
                resultMap.put("processingFee", cost.setScale(4, BigDecimal.ROUND_HALF_UP));
            }
        }

        //获取运费信息
        SerializeObject resultRep = rateSettingsService.get(RateKeyEnum.FREIGHT.getKey());
        if (resultRep != null && resultRep.getData() != null) {
            JSONObject json = JSON.parseObject(JSONObject.toJSONString(resultRep.getData()));
            resultMap.put("freight", json.getIntValue("fee"));
        }
        return new SerializeObject<>(ResultType.NORMAL, resultMap);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public SerializeObject pay(ExtractionGoldPayBean payParamBean, String memberId) {
        //定义返回类型
        Map<String, Object> resultMap = null;
        // 1、获取分布式锁防止重复调用 =====================================================
        String orderSubmitKey = PayDistributePrefix.EXTRACT_GOLD_ORDER_SUBMIT + payParamBean.getTbillNo();
        // 2、获取分布式锁进行对账户锁定 =====================================================
        if (redisGlobalLock.lock(orderSubmitKey, CommonConstants.PAY_ORDER_SUBMIT_LOCK_TIME, TimeUnit.MILLISECONDS)) {
            //根据绑定银行卡获取银行卡相关信息
            BankCard bankCard = bankCardMapper.findDefaultByMemberId(memberId);
            Ensure.that(bankCard == null).isTrue("17000419");
            payParamBean.setBankCardId(bankCard.getId());
            //提金订单单号
            String orderNo = OrderNOPrefixEnum.EG.name() + SerialNumberWorker.getInstance().nextId();

            // 1、获取分布式锁防止重复调用 =====================================================
            String key = PayDistributePrefix.PAY_MEMBER_ACCOUNT + memberId;
            if (redisGlobalLock.lock(key)) {
                try {
                    PayTbill payTbill = payTbillMapper.selectByOrderNO(payParamBean.getTbillNo());
                    Ensure.that(payTbill == null).isTrue("00000003");

                    //获取账户余额
                    MemberAccount memberAccount = memberAccountMapper.findByMemberId(memberId);
                    Ensure.that(memberAccount == null).isTrue("00000003");

                    //支付总金额
                    BigDecimal amount = payParamBean.getActualAmount();
                    //生成本地交易信息
                    Trade trade = tradeMapper.queryTradeByOrderId(orderNo);
                    if (trade == null) {
                        trade = Trade.convertBean(payParamBean, memberId, orderNo);
                        //设置实际支付金额
                        if (memberAccount.getUsableAmount().compareTo(amount) < 0) {
                            BigDecimal payAmount = BigDecimalUtil.to2Point(amount.subtract(memberAccount.getUsableAmount()));   //银行卡实际支付金额
                            trade.setPayAmount(payAmount);
                        }
                        //设置费率  运费+加工费
                        if (payParamBean.getShopId() == null) {
                            trade.setFee(BigDecimalUtil.to2Point(payParamBean.getCourierFee().add(payParamBean.getProcessingFee())));
                        }else {
                            trade.setFee(BigDecimalUtil.to2Point(payParamBean.getProcessingFee()));
                        }

                        tradeMapper.insert(trade);
                    }

                    //余额支付  余额足够的时候
                    if (memberAccount.getUsableAmount().compareTo(amount) >= 0) {
                        BigDecimal fundAmount = BigDecimalUtil.to2Point(memberAccount.getFundAmount().subtract(amount));
                        BigDecimal usableAmount = BigDecimalUtil.to2Point(memberAccount.getUsableAmount().subtract(amount));
                        //扣除账户余额
                        Map<String, Object> param = new HashMap<String, Object>();
                        param.put("id", memberAccount.getId());
                        param.put("fundAmount", fundAmount);
                        param.put("usableAmount", usableAmount);
                        memberAccountMapper.updateByPrimaryKeySelective(param);
                        //提金 新增提金订单信息
                        ExtractGoldBaseBean extractGoldBaseBean = new ExtractGoldBaseBean();
                        extractGoldBaseBean.setStatus(ExtractGoldStatusEnum.SUBSCRIBE.getStatus());
                        extractGoldBaseBean.setFullname(payParamBean.getFullname());
                        extractGoldBaseBean.setCellphone(payParamBean.getCellphone());
                        extractGoldBaseBean.setMemberId(memberId);
                        extractGoldBaseBean.setProcessingFee(payParamBean.getProcessingFee());
                        extractGoldBaseBean.setActualAmount(payParamBean.getActualAmount());
                        extractGoldBaseBean.setFee(BigDecimal.ZERO);
                        extractGoldBaseBean.setTbillNo(payParamBean.getTbillNo());
                        extractGoldBaseBean.setOrderNo(orderNo);
                        extractGoldBaseBean.setSuccessTime(DateUtils.getCurrentDateStr());
                        extractGoldBaseBean.setReaded(0);

                        if (payParamBean.getShopId() == null) {
                            extractGoldBaseBean.setAddress(payParamBean.getAddress());
                            extractGoldBaseBean.setCourierFee(payParamBean.getCourierFee());
                            int rows = entityExtractGoldMapper.insert(extractGoldBaseBean);
                            Ensure.that(rows).isLt(1, "00000005");
                        } else {
                            extractGoldBaseBean.setShopId(payParamBean.getShopId());
                            SerializeObject<GoldShopBean> object = goldShopService.getShopDetail(payParamBean.getShopId());
                            if (object != null && object.getData() != null) {
                                extractGoldBaseBean.setShopName(object.getData().getName());
                            }
                            int rows = extractionOfflineMapper.insert(extractGoldBaseBean);
                            Ensure.that(rows).isLt(1, "00000005");
                        }

                        //更新订单交易记录
                        Trade trades = new Trade();
                        trades.setSerialNumber(orderNo);
                        trades.setStatus(CommonConstants.PayStatus.YESPAY.getIndex());
                        tradeMapper.updatePayStatus(trades);

                        //支出明细
                        BillBean billBean = cn.ug.pay.utils.Common.getBillBean(trade);
                        billBean.setType(BillType.OUTLAY.getValue());
                        billBean.setGoldPrice(payTbill.getGoldPrice());
                        billBean.setTradeType(TradeType.GOLD_EXTRACTION.getValue());
                        //更新支出明细
                        billService.save(billBean);


                        //增加账户余额变动消息队列
                        payCommon.accountChangeMsgQueue(memberId, cn.ug.msg.bean.status.CommonConstants.MsgType.ACCOUNT_PAY_CHANGE.getIndex(),
                                BigDecimalUtil.to2Point(amount).toString(), fundAmount.toString());

                        //统计分析成功--交易
                        MemberAnalyseMsgParamBean analyse1 = new MemberAnalyseMsgParamBean();
                        analyse1.setMemberId(trade.getMemberId());
                        analyse1.setType(cn.ug.analyse.bean.status.CommonConstants.MemberAnalyseType.TRADE.getIndex());
                        amqpTemplate.convertAndSend(QUEUE_MEMBER_ANALYSE, analyse1);
                        logger.info("-----统计分析-----");

                        //支付成功能 提单相关表状态修改
                        payExtractionSuccess(extractGoldBaseBean.getTbillNo(), memberId);

                        //发送提金预约和提金成功短信
                        Msg subscribeMap = new Msg();
                        subscribeMap.setMemberId(trade.getMemberId());
                        subscribeMap.setType(cn.ug.msg.bean.status.CommonConstants.MsgType.EXTRACTGOLD_SUBSCRIBE.getIndex());
                        amqpTemplate.convertAndSend(QUEUE_MSG_SEND, subscribeMap);

                        Msg msg = new Msg();
                        msg.setMemberId(trade.getMemberId());
                        msg.setType(cn.ug.msg.bean.status.CommonConstants.MsgType.EXTRACTGOLD_FINISH.getIndex());
                        Map<String, String> paramMap = new HashMap<>();
                        paramMap.put("productName", payTbill.getProductName());
                        paramMap.put("amount", amount.toString());
                        msg.setParamMap(paramMap);
                        amqpTemplate.convertAndSend(QUEUE_MSG_SEND, msg);

                        //提金预约微信推送
                        wxSubscribeSend(memberId, payTbill.getProductName(), payParamBean.getAddress(), payParamBean.getFullname(), payParamBean.getCellphone());
                        return new SerializeObject(ResultType.NORMAL, "00000001", orderNo);
                    } else {
                        //验证银行是否维护中
                        BankInfoBean bankInfo = bankInfoMapper.queryBankInfo(bankCard.getBankCode());
                        if (bankInfo != null && CommonConstants.CardStatus.MAINTENANCE.getIndex() == bankInfo.getStatus()) {
                            Msg msg = new Msg();
                            msg.setMemberId(trade.getMemberId());
                            msg.setType(cn.ug.msg.bean.status.CommonConstants.MsgType.BANK_MAINTENANCE.getIndex());
                            Map<String, String> paramMap = new HashMap<>();
                            paramMap.put("bankName", cn.ug.util.StringUtils.sensitivityBankCard(bankCard.getCardNo()));
                            msg.setParamMap(paramMap);
                            amqpTemplate.convertAndSend(QUEUE_MSG_SEND, msg);
                            Ensure.that(CommonConstants.CardStatus.MAINTENANCE.getIndex() == bankInfo.getStatus()).isTrue("17000423");
                        }

                        //提金 新增提金订单信息
                        ExtractGoldBaseBean extractGoldBaseBean = new ExtractGoldBaseBean();
                        extractGoldBaseBean.setStatus(ExtractGoldStatusEnum.SUBSCRIBE.getStatus());
                        extractGoldBaseBean.setFullname(payParamBean.getFullname());
                        extractGoldBaseBean.setCellphone(payParamBean.getCellphone());
                        extractGoldBaseBean.setMemberId(memberId);
                        extractGoldBaseBean.setProcessingFee(payParamBean.getProcessingFee());
                        extractGoldBaseBean.setActualAmount(payParamBean.getActualAmount());
                        extractGoldBaseBean.setFee(BigDecimal.ZERO);
                        extractGoldBaseBean.setTbillNo(payParamBean.getTbillNo());
                        extractGoldBaseBean.setOrderNo(orderNo);
                        extractGoldBaseBean.setSuccessTime(DateUtils.getCurrentDateStr());
                        extractGoldBaseBean.setReaded(0);

                        if (payParamBean.getShopId() == null) {
                            extractGoldBaseBean.setAddress(payParamBean.getAddress());
                            extractGoldBaseBean.setCourierFee(payParamBean.getCourierFee());
                            int rows = entityExtractGoldMapper.insert(extractGoldBaseBean);
                            Ensure.that(rows).isLt(1, "00000005");
                        } else {
                            extractGoldBaseBean.setShopId(payParamBean.getShopId());
                            SerializeObject<GoldShopBean> object = goldShopService.getShopDetail(payParamBean.getShopId());
                            if (object != null && object.getData() != null) {
                                extractGoldBaseBean.setShopName(object.getData().getName());
                            }
                            int rows = extractionOfflineMapper.insert(extractGoldBaseBean);
                            Ensure.that(rows).isLt(1, "00000005");
                        }

                        SerializeObject rateBean = rateSettingsService.get(RateKeyEnum.RECHARGE.getKey());
                        BigDecimal fee = BigDecimal.ZERO;
                        if (rateBean != null && rateBean.getData() != null) {
                            JSONObject json = JSON.parseObject(JSONObject.toJSONString(rateBean.getData()));
                            int dayNum = billMapper.getTransactionNumForThisDay(memberId, CommonConstants.PayType.RECHARGE.getIndex());
                            int monthNum = billMapper.getTransactionNumForThisMonth(memberId, CommonConstants.PayType.RECHARGE.getIndex());
                            fee = fundRateConfig.getFee(json, amount.subtract(memberAccount.getUsableAmount()), dayNum, monthNum);
                        }
                        amount = BigDecimalUtil.to2Point(amount.add(fee));
                        //设置付款金额
                        payParamBean.setActualAmount(BigDecimalUtil.to2Point(amount.subtract(memberAccount.getUsableAmount())));
                        //设置公共类
                        BankCardBean bankCardBean = dozerBeanMapper.map(bankCard, BankCardBean.class);
                        TradeCommonParamBean entity = dozerBeanMapper.map(payParamBean, TradeCommonParamBean.class);
                        entity.setAmount(payParamBean.getActualAmount());
                        entity.setOrderId(orderNo);
                        entity.setMemberId(memberId);
                        entity.setBankCardBean(bankCardBean);
                        entity.setPayAmount(BigDecimalUtil.to2Point(amount));
                        entity.setType(payParamBean.getType());
                        entity.setTitle(payTbill.getProductName());
                        //选择支付方式
                        switch (payParamBean.getWay()) {
                            case TradeStatus.PayWay.yeePay:
                                resultMap = yeePayCommons.prepayOrder(entity);
                                break;


                        }
                        if (resultMap != null && !resultMap.isEmpty()) {
                            return new SerializeObject(ResultType.ERROR, resultMap.get("msg") + "");
                        } else {
                            return new SerializeObject(ResultType.NORMAL, "00000001", orderNo);
                        }
                    }
                } catch (Exception e) {
                    logger.error("---支付捕获异常成功--", e);
                    throw e;
                } finally {
                    // 4、释放分布式锁
                    redisGlobalLock.unlock(key);
                }
            }
        } else {
            // 如果没有获取锁
            logger.info("-------没有获取到锁-------");
            Ensure.that(true).isTrue("17000706");
        }
        return new SerializeObject(ResultType.NORMAL, "00000001", resultMap);
    }

    /**
     * 提金支付成功后操作 提单表，提单状态变更表，以及提单账户统计表信息
     *
     * @param tbillNo
     * @param memberId
     */
    @Transactional(rollbackFor = Exception.class)
    public void payExtractionSuccess(String tbillNo, String memberId) {
        //1. pay_tbill 提单表信息修改
        PayTbill payTbill = payTbillMapper.selectByOrderNO(tbillNo);
        int rows = 0;
        if (payTbill != null) {
            Map<String, Object> tbillParam = new HashMap<String, Object>();
            tbillParam.put("orderNO", tbillNo);
            tbillParam.put("status", TbillStatusEnum.FROZEN.getStatus());
            tbillParam.put("modifyTime", UF.getFormatDateTime(UF.getDateTime()));
            //提单冻结时间新增
            tbillParam.put("frozenTime", UF.getFormatDateTime(UF.getDateTime()));
            tbillParam.put("readed", 0);
            rows = payTbillMapper.update(tbillParam);
            Ensure.that(rows).isLt(1, "00000005");
        }

        //2. pay_tbill_status 记录新增
        PayTbillStatus payTbillStatus = new PayTbillStatus();
        payTbillStatus.setOrderNO(SerialNumberWorker.getInstance().nextId());
        payTbillStatus.setTbillNO(tbillNo);
        payTbillStatus.setStatus(TbillStatusEnum.FROZEN.getStatus());
        payTbillStatus.setType("提金");
        payTbillStatus.setRemark("提金预约");
        rows = payTbillStatusMapper.insert(payTbillStatus);
        Ensure.that(rows).isLt(1, "00000005");

        //3. pay_tbill_statistics 提单统计表信息修改
        PayTbillStatistics payTbillStatistics = payTbillStatisticsMapper.selectByMemberId(memberId);
        if (payTbillStatistics != null) {
            Map<String, Object> tbillStatisticsParam = new HashMap<String, Object>();
            tbillStatisticsParam.put("pendingBills", payTbillStatistics.getPendingBills() - 1);
            tbillStatisticsParam.put("pendingGram", payTbillStatistics.getPendingGram() - payTbill.getTotalGram());
            tbillStatisticsParam.put("frozenBills", payTbillStatistics.getFrozenBills() + 1);
            tbillStatisticsParam.put("frozenGram", payTbillStatistics.getFrozenGram() + payTbill.getTotalGram());
            tbillStatisticsParam.put("memberId", memberId);
            rows = payTbillStatisticsMapper.update(tbillStatisticsParam);
            Ensure.that(rows).isLt(1, "00000005");
        }


    }

    /**
     * 提金完成
     *
     * @param tbillNo
     * @param memberId
     */
    public void extractionFinished(String tbillNo, String memberId) {
        //1. pay_tbill 提单表信息修改
        int rows = 0;
        PayTbill payTbill = payTbillMapper.selectByOrderNO(tbillNo);
        if (payTbill != null) {
            Map<String, Object> tbillParam = new HashMap<String, Object>();
            tbillParam.put("orderNO", tbillNo);
            tbillParam.put("status", TbillStatusEnum.GOLD_EXTRACTION.getStatus());
            tbillParam.put("modifyTime", UF.getFormatDateTime(UF.getDateTime()));
            tbillParam.put("readed", 0);
            rows = payTbillMapper.update(tbillParam);
            Ensure.that(rows).isLt(1, "00000005");
        }

        //2. pay_tbill_status 新增记录
        PayTbillStatus payTbillStatus = new PayTbillStatus();
        payTbillStatus.setOrderNO(SerialNumberWorker.getInstance().nextId());
        payTbillStatus.setTbillNO(tbillNo);
        payTbillStatus.setStatus(TbillStatusEnum.GOLD_EXTRACTION.getStatus());
        payTbillStatus.setType("提金");
        payTbillStatus.setRemark("提金成功");
        rows = payTbillStatusMapper.insert(payTbillStatus);
        Ensure.that(rows).isLt(1, "00000005");

        //3. pay_tbill_statistics 提单统计表信息修改
        PayTbillStatistics payTbillStatistics = payTbillStatisticsMapper.selectByMemberId(memberId);
        if (payTbillStatistics != null) {
            Map<String, Object> tbillStatisticsParam = new HashMap<String, Object>();
            tbillStatisticsParam.put("frozenBills", payTbillStatistics.getFrozenBills() - 1);
            tbillStatisticsParam.put("frozenGram", payTbillStatistics.getFrozenGram() - payTbill.getTotalGram());
            tbillStatisticsParam.put("extractedBills", payTbillStatistics.getExtractedBills() + 1);
            tbillStatisticsParam.put("extractedGram", payTbillStatistics.getExtractedGram() + payTbill.getTotalGram());
            tbillStatisticsParam.put("memberId", memberId);
            rows = payTbillStatisticsMapper.update(tbillStatisticsParam);
            Ensure.that(rows).isLt(1, "00000005");
        }
    }

    /**
     * 提金取消
     *
     * @param tbillNo
     * @param memberId
     */
    @Transactional(rollbackFor = Exception.class)
    public void closeExtractionOrder(String tbillNo, String memberId, String orderNo) {
        // 1、获取分布式锁防止重复调用 =====================================================
        String key = PayDistributePrefix.PAY_MEMBER_ACCOUNT + memberId;
        if (redisGlobalLock.lock(key)) {
            try {
                PayTbill payTbill = payTbillMapper.selectByOrderNO(tbillNo);
                int rows = 0;
                if (payTbill != null) {
                    Map<String, Object> tbillParam = new HashMap<String, Object>();
                    tbillParam.put("orderNO", tbillNo);
                    tbillParam.put("status", TbillStatusEnum.PAY_SUCCESS.getStatus());
                    tbillParam.put("modifyTime", UF.getFormatDateTime(UF.getDateTime()));
                    tbillParam.put("readed", 0);
                    rows = payTbillMapper.update(tbillParam);
                    Ensure.that(rows).isLt(1, "00000005");
                }

                //2. pay_tbill_status 记录新增
                PayTbillStatus payTbillStatus = new PayTbillStatus();
                payTbillStatus.setOrderNO(SerialNumberWorker.getInstance().nextId());
                payTbillStatus.setTbillNO(tbillNo);
                payTbillStatus.setStatus(TbillStatusEnum.PAY_SUCCESS.getStatus());
                payTbillStatus.setType("购买");
                payTbillStatus.setRemark("取消提金");
                rows = payTbillStatusMapper.insert(payTbillStatus);
                Ensure.that(rows).isLt(1, "00000005");

                //3. pay_tbill_statistics 提单统计表信息修改
                PayTbillStatistics payTbillStatistics = payTbillStatisticsMapper.selectByMemberId(memberId);
                if (payTbillStatistics != null) {
                    Map<String, Object> tbillStatisticsParam = new HashMap<String, Object>();
                    tbillStatisticsParam.put("pendingBills", payTbillStatistics.getPendingBills() + 1);
                    tbillStatisticsParam.put("pendingGram", payTbillStatistics.getPendingGram() + payTbill.getTotalGram());
                    tbillStatisticsParam.put("frozenBills", payTbillStatistics.getFrozenBills() - 1);
                    tbillStatisticsParam.put("frozenGram", payTbillStatistics.getFrozenGram() - payTbill.getTotalGram());
                    tbillStatisticsParam.put("memberId", memberId);
                    rows = payTbillStatisticsMapper.update(tbillStatisticsParam);
                    Ensure.that(rows).isLt(1, "00000005");
                }

                //取消提金订单 账户余额返还
                Trade trade = tradeMapper.queryTradeByOrderId(orderNo);
                if (trade != null) {
                    //处理已支付订单
                    if (cn.ug.pay.bean.status.CommonConstants.PayStatus.YESPAY.getIndex() == trade.getStatus()) {
                        MemberAccount memberAccount = memberAccountMapper.findByMemberId(trade.getMemberId());
                        Ensure.that(memberAccount == null).isTrue("17000421");
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("id", memberAccount.getId());
                        map.put("fundAmount", memberAccount.getFundAmount().add(trade.getAmount()));
                        map.put("usableAmount", memberAccount.getUsableAmount().add(trade.getAmount()));
                        rows = memberAccountMapper.updateByPrimaryKeySelective(map);
                        Ensure.that(rows).isLt(1, "00000005");

                        //支出明细
                        BillBean billBean = cn.ug.pay.utils.Common.getBillBean(trade);
                        billBean.setFee(new BigDecimal(0));
                        billBean.setType(BillType.INCOME.getValue());
                        billBean.setGoldPrice(payTbill.getGoldPrice());
                        billBean.setActualAmount(billBean.getAmount());
                        billBean.setTradeType(TradeType.GOLD_EXTRACTION_CLOSE_RETURN.getValue());
                        //更新支出明细
                        billService.save(billBean);
                    }
                }
            } catch (Exception e) {
                throw e;
            } finally {
                // 4、释放分布式锁 ================================================================
                redisGlobalLock.unlock(key);
            }
        } else {
            // 如果没有获取锁
            Ensure.that(true).isTrue("17000706");
        }
    }

    private void sendNotice(ExtractGoldBaseBean extractGoldBaseBean,String orderNo){
        /**
         *  提金订单关闭  提单，提单状态，提单用户统计相关表状态修改
         */
        closeExtractionOrder(extractGoldBaseBean.getTbillNo(), extractGoldBaseBean.getMemberId(), orderNo);
        //短信通知
        Msg subscribeMap = new Msg();
        subscribeMap.setMemberId(extractGoldBaseBean.getMemberId());
        subscribeMap.setType(cn.ug.msg.bean.status.CommonConstants.MsgType.EXTRACTGOLD_CANCEL.getIndex());
        amqpTemplate.convertAndSend(QUEUE_MSG_SEND, subscribeMap);

        //微信推送
        wxCloseSend(extractGoldBaseBean.getMemberId(), "取消提金");
    }
    /**
     * 支付完成后进行微信提金预约通知
     *
     * @param memberId
     * @param productName 商品名称
     * @param address     收货地址
     * @param fullname    收货人
     * @param cellphone   收货电话
     */
    @Override
    public void wxSubscribeSend(String memberId, String productName, String address, String fullname, String cellphone) {
        WxTemplateEnum wxTemplateEnum = WxTemplateEnum.getWxTemplateByCode(WxTemplateEnum.EXTRACT_GOLD_SUBSCRIBE.getType());
        WxMessageParamBean wxMessageParamBean = new WxMessageParamBean();
        wxMessageParamBean.setMemberId(memberId);
        //消息推送类型
        wxMessageParamBean.setType(WxTemplateEnum.EXTRACT_GOLD_SUBSCRIBE.getType());
        WxNotifyData wxNotifyData = new WxNotifyData();

        Map<String, WxNotifyData.TemplateDataAttr> wxParamMap = new HashMap();
        WxNotifyData.TemplateDataAttr first = new WxNotifyData.TemplateDataAttr();
        first.setDataValue(wxTemplateEnum.getFirstData());
        wxParamMap.put("first", first);

        WxNotifyData.TemplateDataAttr keyword1 = new WxNotifyData.TemplateDataAttr();
        keyword1.setDataValue(productName);
        wxParamMap.put("keyword1", keyword1);

        WxNotifyData.TemplateDataAttr keyword2 = new WxNotifyData.TemplateDataAttr();
        keyword2.setDataValue(address);
        wxParamMap.put("keyword2", keyword2);

        WxNotifyData.TemplateDataAttr keyword3 = new WxNotifyData.TemplateDataAttr();
        keyword3.setDataValue(fullname);
        wxParamMap.put("keyword3", keyword3);

        WxNotifyData.TemplateDataAttr keyword4 = new WxNotifyData.TemplateDataAttr();
        keyword4.setDataValue(cellphone);
        wxParamMap.put("keyword4", keyword4);

        WxNotifyData.TemplateDataAttr remark = new WxNotifyData.TemplateDataAttr();
        remark.setDataValue(wxTemplateEnum.getRemark());
        wxParamMap.put("remark", remark);

        wxNotifyData.setData(wxParamMap);
        wxMessageParamBean.setTemplateData(wxNotifyData);
        amqpTemplate.convertAndSend(QUEUE_MSG_WX_SEND, wxMessageParamBean);
    }

    /**
     * 提金取消或者支付失败
     *
     * @param memberId
     * @param statusMsg
     */
    public void wxCloseSend(String memberId, String statusMsg) {
        WxTemplateEnum wxTemplateEnum = WxTemplateEnum.getWxTemplateByCode(WxTemplateEnum.EXTRACT_GOLD_CLOSE.getType());
        WxMessageParamBean wxMessageParamBean = new WxMessageParamBean();
        wxMessageParamBean.setMemberId(memberId);
        //消息推送类型
        wxMessageParamBean.setType(WxTemplateEnum.EXTRACT_GOLD_CLOSE.getType());
        WxNotifyData wxNotifyData = new WxNotifyData();

        Map<String, WxNotifyData.TemplateDataAttr> wxParamMap = new HashMap();
        WxNotifyData.TemplateDataAttr first = new WxNotifyData.TemplateDataAttr();
        first.setDataValue(wxTemplateEnum.getFirstData());
        wxParamMap.put("first", first);

        WxNotifyData.TemplateDataAttr keyword1 = new WxNotifyData.TemplateDataAttr();
        keyword1.setDataValue(statusMsg);
        wxParamMap.put("keyword1", keyword1);

        WxNotifyData.TemplateDataAttr keyword2 = new WxNotifyData.TemplateDataAttr();
        keyword2.setDataValue(DateUtils.getCurrentDateStr());
        wxParamMap.put("keyword2", keyword2);

        WxNotifyData.TemplateDataAttr remark = new WxNotifyData.TemplateDataAttr();
        remark.setDataValue(wxTemplateEnum.getRemark());
        wxParamMap.put("remark", remark);

        wxNotifyData.setData(wxParamMap);
        wxMessageParamBean.setTemplateData(wxNotifyData);
        amqpTemplate.convertAndSend(QUEUE_MSG_WX_SEND, wxMessageParamBean);
    }

}